const { clipboard } = require("electron");
const windowInfoAddon = require("./win32/windowInfoAddon/build/Release/windowInfoAddon.node");
const {
  simulateCopyEvent,
} = require("./win32/simulateCopyEvent/build/Release/simulateCopyEvent.node");
const logger = require("./log.cjs");
const keycode = {
  ctrl: 29,
  c: 46,
  v: 47,
};
function delayTime(time = 1000) {
  return new Promise(function (resolve) {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
}

function isDev() {
  return process.env.NODE_ENV === "development";
}

function once(cb) {
  let isRun = false;
  return () => {
    if (!isRun) {
      cb && cb();
      isRun = true;
    }
  };
}

const activeWindowName = () => {
  return new Promise((resolve, reject) => {
    windowInfoAddon.getActiveWindowInfo((str) => {
      resolve(str);
    });
  });
};

const getSelectedText = (delay = 50, stack) => {
  return new Promise(async (resolve, reject) => {
    await delayTime(300)
    const lastText = clipboard.readText("clipboard");
    const image = clipboard.readImage()
    const platform = process.platform;
    let keyType = checkKeyGroup(stack);
    try {
      if (keyType === "copy") {
        content = clipboard.readText("clipboard");
        resolve(content.replace(/\n/g, " "));
        stack.clear();
        return;
      }
      if (keyType === "ctrl" || keyType === "paste") {
        resolve("");
        stack.clear();
        return;
      }
      if (platform === "darwin") {
        //TODO macos后续实现
      } else {
        clipboard.writeText("");
        simulateCopyEvent();
        // const robot = require('robotjs');
        // 模拟按下Ctrl+C组合键
        // robot.keyTap('c', 'control');
      }
    } catch (error) {
      console.log(error);
      logger.error(JSON.stringify(error));
    }
    setTimeout(() => {
      const content = clipboard.readText("clipboard") || "";
      clipboard.writeText(lastText);
      if(!image.isEmpty()) clipboard.writeImage(image);
      resolve(content.replace(/\n/g, " "));
      if(stack) stack.clear();
    }, delay);
  });
};

const checkKeyGroup = (stack) => {
  if(!stack) return "normal";
  if (stack.size === 0) return "normal";
  const arr = [...stack];
  if (arr[0] == keycode.ctrl && arr[1] == keycode.c) {
    return "copy";
  } else if (arr[0] == keycode.ctrl && arr[1] == keycode.v) {
    return "paste";
  } else if (arr.length === 1 && arr[0] === keycode.ctrl) {
    return "ctrl";
  } else {
    return "normal";
  }
};

module.exports = {
  delayTime,
  once,
  getSelectedText,
  activeWindowName,
  isDev,
  checkKeyGroup,
  keycode,
};
